﻿#include "websocketserver.h"
#include <QDebug>
#include <QWebSocket>
#include <QDir>
#include "../dlgstart.h"

websocketserver::websocketserver(quint16 port, QObject *parent) : QObject(parent)
{
    m_websocketWebEdit = NULL;
    m_websocketWebWrite = NULL;
    m_parent = parent;
    m_websocketServer = new QWebSocketServer("clientserver",QWebSocketServer::NonSecureMode,this);
    if(m_websocketServer->listen(QHostAddress::Any, port))
    {
        connect(m_websocketServer,&QWebSocketServer::newConnection,this,&websocketserver::onNewConnection,Qt::QueuedConnection);
        connect(m_websocketServer,&QWebSocketServer::closed, this,&websocketserver::onClosed);
        qDebug() << "clientService: websocket server listen success!!!";
    }
    else
    {
        qDebug() << "clientService: websocket server listen fail! websocket server listen fail!!!";
    }
}

websocketserver::~websocketserver()
{
}

bool websocketserver::pushMessageToRobot(QString message)
{
    bool bResult = false;
    if(m_websocketWebEdit) {
        qint64 nLen = m_websocketWebEdit->sendTextMessage(message);
        m_websocketWebEdit->flush();
        if(nLen > 0)
            bResult = true;
    }
    return bResult;
}

bool websocketserver::sendToClient(QWebSocket *socket, QString message)
{
    bool bResult = false;
    if(socket){
        qint64 nLen = socket->sendTextMessage(message);
        if(nLen > 1)
            bResult = true;
    }
    return bResult;
}

void websocketserver::onNewConnection()
{
    QWebSocket *socket = m_websocketServer->nextPendingConnection();
    connect(socket,&QWebSocket::textMessageReceived,this,&websocketserver::textMessageReceived,Qt::QueuedConnection);
    connect(socket,&QWebSocket::disconnected,this,&websocketserver::disconnectwebsock);
    QString szUrl = socket->requestUrl().toString();
    if("webEdit" == szUrl.right(7)){
        //网页编辑端
        m_websocketWebEdit = socket;
        DlgStart *parent = (DlgStart*)m_parent;
        QString szLog = QString("select * from t_basiconfig");
        if(parent->m_dbquery->exec(szLog))
        {
            bool bSend = false;
            QJsonObject obj;
            obj.insert("cmd", "basiconfig");
            int nonebyoneupway = parent->m_dbquery->record().indexOf("onebyoneupway");
            int nactivityName = parent->m_dbquery->record().indexOf("activityName");
            int nactivityNum = parent->m_dbquery->record().indexOf("activityNum");
            int nactivityPwd = parent->m_dbquery->record().indexOf("activityPwd");
            int nsignInBackMusic = parent->m_dbquery->record().indexOf("signInBackMusic");
            int nsignSucBackMusic = parent->m_dbquery->record().indexOf("signSucBackMusic");
            int nbrushColor = parent->m_dbquery->record().indexOf("brushColor");
            int nspeakername = parent->m_dbquery->record().indexOf("speakername");
            int nspeakerSpeed = parent->m_dbquery->record().indexOf("speakerSpeed");
            int nspeakerPicth = parent->m_dbquery->record().indexOf("speakerPicth");
            int nbeginTts = parent->m_dbquery->record().indexOf("beginTts");
            int nrandomTts1 = parent->m_dbquery->record().indexOf("randomTts1");
            int nrandomTts2 = parent->m_dbquery->record().indexOf("randomTts2");
            int nrandomTts3 = parent->m_dbquery->record().indexOf("randomTts3");
            int nendTts = parent->m_dbquery->record().indexOf("endTts");
            int nimgwidth = parent->m_dbquery->record().indexOf("backimgwidth");
            int nimgheight = parent->m_dbquery->record().indexOf("backimgheight");
            while(parent->m_dbquery->next())
            {
                bool bOnebyoneupway = parent->m_dbquery->value(nonebyoneupway).toBool();
                QString activityName = parent->m_dbquery->value(nactivityName).toString();
                QString activityNum = parent->m_dbquery->value(nactivityNum).toString();
                QString activityPwd = parent->m_dbquery->value(nactivityPwd).toString();
                QString signInBackMusic = parent->m_dbquery->value(nsignInBackMusic).toString();
                QString signSucBackMusic = parent->m_dbquery->value(nsignSucBackMusic).toString();
                QString brushColor = parent->m_dbquery->value(nbrushColor).toString();
                QString speakername = parent->m_dbquery->value(nspeakername).toString();
                QString speakerSpeed = parent->m_dbquery->value(nspeakerSpeed).toString();
                QString speakerPicth = parent->m_dbquery->value(nspeakerPicth).toString();
                QString beginTts = parent->m_dbquery->value(nbeginTts).toString();
                QString randomTts1 = parent->m_dbquery->value(nrandomTts1).toString();
                QString randomTts2 = parent->m_dbquery->value(nrandomTts2).toString();
                QString randomTts3 = parent->m_dbquery->value(nrandomTts3).toString();
                QString endTts = parent->m_dbquery->value(nendTts).toString();
                QString imgwidth = parent->m_dbquery->value(nimgwidth).toString();
                QString imgheight = parent->m_dbquery->value(nimgheight).toString();
                obj.insert("onebyoneupway", bOnebyoneupway);
                obj.insert("activityName", activityName);
                obj.insert("activityNum", activityNum);
                obj.insert("activityPwd", activityPwd);
                obj.insert("signInBackMusic", signInBackMusic);
                obj.insert("signSucBackMusic", signSucBackMusic);
                obj.insert("brushColor", brushColor);
                obj.insert("speakername", speakername);
                obj.insert("speakerSpeed", speakerSpeed);
                obj.insert("speakerPicth", speakerPicth);
                obj.insert("beginTts", beginTts);
                obj.insert("randomTts1", randomTts1);
                obj.insert("randomTts2", randomTts2);
                obj.insert("randomTts3", randomTts3);
                obj.insert("endTts", endTts);
                obj.insert("backimgwidth",imgwidth);
                obj.insert("backimgheight",imgheight);
                bSend = true;
            }
            if(bSend){
                QJsonDocument jsonDoc;
                jsonDoc.setObject(obj);
                QByteArray byteArray = jsonDoc.toJson(QJsonDocument::Compact);
                sendToClient(socket, QString(byteArray));
            }
        }
        szLog = QString("select * from t_wallLabel");
        if(parent->m_dbquery->exec(szLog))
        {
            bool bSend = false;
            QJsonObject obj;
            obj.insert("cmd", "coordsLabspush");
            QJsonArray array;
            int nleft = parent->m_dbquery->record().indexOf("left");
            int ntop = parent->m_dbquery->record().indexOf("top");
            int nwidth = parent->m_dbquery->record().indexOf("width");
            int nheight = parent->m_dbquery->record().indexOf("height");
            int nsigndname = parent->m_dbquery->record().indexOf("signdname");
            while(parent->m_dbquery->next())
            {
                QString signdname = parent->m_dbquery->value(nsigndname).toString();
                int left = parent->m_dbquery->value(nleft).toInt();
                int top = parent->m_dbquery->value(ntop).toInt();
                int width = parent->m_dbquery->value(nwidth).toInt();
                int height = parent->m_dbquery->value(nheight).toInt();
                QJsonObject childObj;
                childObj.insert("top",top);
                childObj.insert("left",left);
                childObj.insert("width",width);
                childObj.insert("height",height);
                childObj.insert("name",signdname);
                array.append(childObj);
                bSend = true;
            }
            if(bSend){
                QJsonValue jsonValue(array);
                obj.insert("data",jsonValue);
                QJsonDocument jsonDoc;
                jsonDoc.setObject(obj);
                QByteArray byteArray = jsonDoc.toJson(QJsonDocument::Compact);
                sendToClient(socket, QString(byteArray));
            }
        }
        //遍历背景音乐文件夹获取文件
        QJsonObject obj_music;
        obj_music.insert("cmd", "obj_music");
        QJsonArray array_musicback;
        QJsonArray array_musicsuc;
        QDir dir("./signwall_backfiles/backgroundmusic");
        foreach(QFileInfo mfi, dir.entryInfoList())
        {
            if(mfi.isFile())
            {
                if("mp3" == mfi.suffix().toLower() || "wav" == mfi.suffix().toLower())
                {
                    QJsonObject childObj_music;
                    childObj_music.insert("music_back",mfi.fileName());
                    array_musicback.append(childObj_music);
                }
            }
        }
        QJsonValue valback(array_musicback);
        obj_music.insert("backmusic", valback);
        QDir dir2("./signwall_backfiles/successmusic");
        foreach(QFileInfo mfi, dir2.entryInfoList())
        {
            if(mfi.isFile())
            {
                if("mp3" == mfi.suffix().toLower() || "wav" == mfi.suffix().toLower())
                {
                    QJsonObject childObj_music;
                    childObj_music.insert("music_suc",mfi.fileName());
                    array_musicsuc.append(childObj_music);
                }
            }
        }
        QJsonValue valsuc(array_musicsuc);
        obj_music.insert("sucmusic", valsuc);
        QJsonDocument jsonDoc_music;
        jsonDoc_music.setObject(obj_music);
        QByteArray byteArrayMusic = jsonDoc_music.toJson(QJsonDocument::Compact);
        sendToClient(socket, QString(byteArrayMusic));
        QDir dirtest;
        qDebug() << byteArrayMusic.data() << ":" << dirtest.currentPath();
    }else if("webWrite" == szUrl.right(8)){
        //手写端
        m_websocketWebWrite = socket;
        DlgStart *parent = (DlgStart*)m_parent;
        QString szLog = QString("select signdname from t_wallLabel");
        if(parent->m_dbquery->exec(szLog))
        {
            bool bSend = false;
            bool bLocalPlace = false;
            QJsonObject obj;
            obj.insert("cmd", "pushnamelist");
            QJsonArray array;
            int nsigndname = parent->m_dbquery->record().indexOf("signdname");
            while(parent->m_dbquery->next())
            {
                QString signdname = parent->m_dbquery->value(nsigndname).toString();
                if(signdname.length() > 0){
                    QJsonObject childObj;
                    childObj.insert("name",signdname);
                    array.append(childObj);
                }else{
                    bLocalPlace = true;
                }
                bSend = true;
            }
            if(bSend){
                QJsonObject childObj;
                if(bLocalPlace){
                    childObj.insert("name",u8"随机位置");
                    array.append(childObj);
                }
                QJsonValue jsonValue(array);
                obj.insert("data",jsonValue);
                QJsonDocument jsonDoc;
                jsonDoc.setObject(obj);
                QByteArray byteArray = jsonDoc.toJson(QJsonDocument::Compact);
                sendToClient(socket, QString(byteArray));
            }
        }
        szLog = QString("select brushColor from t_basiconfig");
        if(parent->m_dbquery->exec(szLog))
        {
            bool bSend = false;
            QJsonObject obj;
            obj.insert("cmd", "pushwriteinfo");
            int nbrushColor = parent->m_dbquery->record().indexOf("brushColor");
            while(parent->m_dbquery->next())
            {
                QString brushColor = parent->m_dbquery->value(nbrushColor).toString();
                obj.insert("brushColor", brushColor);
                bSend = true;
            }
            if(bSend){
                QJsonDocument jsonDoc;
                jsonDoc.setObject(obj);
                QByteArray byteArray = jsonDoc.toJson(QJsonDocument::Compact);
                sendToClient(socket, QString(byteArray));
            }
        }
    }else{
        qDebug() << "clientService: onNewConnection url Error=" << socket->requestUrl().toString();
    }
}

void websocketserver::onClosed()
{

}

void websocketserver::textMessageReceived(QString message)
{
    QWebSocket *socket = qobject_cast<QWebSocket *>(sender());
    if(socket){
        QString szUrl = socket->requestUrl().toString();
        if("webEdit" == szUrl.right(7)){
            //网页编辑端
            parseWebEdit(socket, message);
        }else if("webWrite" == szUrl.right(8)){
            //网页手写端
            parseWebWrite(socket, message);
        }else{
            qDebug() << "clientService: textMessageReceived url Error=" << socket->requestUrl().toString();
        }
    }else{
        qDebug() << "clientService: textMessageReceived socket = null";
    }
}

void websocketserver::disconnectwebsock()
{
    QWebSocket *socket = qobject_cast<QWebSocket *>(sender());
    if (socket) {
        qDebug() << "clientService: websocket server disconnect";
        socket->deleteLater();
    }
}

void websocketserver::parseWebEdit(QWebSocket *socket, QString message)
{
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8(), &error);
    if(QJsonParseError::NoError != error.error)
        return;
    if(!doc.isObject())
        return;
    QJsonObject obj = doc.object();
    QString szcmd = obj.take("cmd").toString();
    if("uploadbackground" == szcmd) {
        QString imagedata = obj.take("data").toString();
        if(!imagedata.isEmpty())
        {
            imagedata.remove(0,imagedata.indexOf(',')); // 去掉Base64源数据头
            QByteArray bytePic = "";
            bytePic = QByteArray::fromBase64(imagedata.toUtf8());
            FILE *tmpJpg = fopen("./httpserver/html/Image/background.png", "wb");
            if(tmpJpg)
            {
                fwrite(bytePic.data(),1,bytePic.size(),tmpJpg);
                fflush(tmpJpg);
                fclose(tmpJpg);
            }
            //
            QJsonObject sendobj;
            sendobj.insert("cmd", "uploadbackground");
            sendobj.insert("result", "ok");
            QJsonDocument jsonDoc;
            jsonDoc.setObject(sendobj);
            QByteArray byteArray = jsonDoc.toJson(QJsonDocument::Compact);
            sendToClient(socket, QString(byteArray));
            emit sigWallRun(0, "");
        }
    }
    else if("coordsLabs" == szcmd) {
        QJsonObject sendobj;
        sendobj.insert("cmd", "coordsLabs");
        sendobj.insert("result", "ok");
        QJsonDocument jsonDoc;
        jsonDoc.setObject(sendobj);
        QByteArray byteArray = jsonDoc.toJson(QJsonDocument::Compact);
        sendToClient(socket, QString(byteArray));
        emit sigWallRun(1, message);
    }
    else if("ctrlactivity" == szcmd) {
        //控制签约上墙仪式 开始或停止
        emit sigWallRun(3, message);
    }
    else if("ctrlQuit" == szcmd){
        //控制下屏显示/隐藏
        emit sigWallRun(4, message);
    }
}

void websocketserver::parseWebWrite(QWebSocket *socket, QString message)
{
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8(), &error);
    if(QJsonParseError::NoError != error.error)
        return;
    if(!doc.isObject())
        return;
    DlgStart *parent = (DlgStart*)m_parent;
    QJsonObject obj = doc.object();
    QString szcmd = obj.take("cmd").toString();
    if("uphandwritePic" == szcmd) {
        QString imagedata = obj.take("data").toString();
        QString name = obj.take("name").toString();
        if(!imagedata.isEmpty())
        {
            imagedata.remove(0,imagedata.indexOf(',')); // 去掉Base64源数据头
            QByteArray bytePic = "";
            bytePic = QByteArray::fromBase64(imagedata.toUtf8());
            uint dateTime = QDateTime::currentDateTime().toTime_t();
            QString szPicName = QString("./signwall_pics/%1.png").arg(dateTime);
            FILE *tmpJpg = fopen(szPicName.toUtf8().data(), "wb");
            if(tmpJpg)
            {
                fwrite(bytePic.data(),1,bytePic.size(),tmpJpg);
                fflush(tmpJpg);
                fclose(tmpJpg);
                QJsonObject sendObj;
                sendObj.insert("picpath", szPicName);
                sendObj.insert("name", name);
                QJsonDocument sendDoc;
                sendDoc.setObject(sendObj);
                QByteArray byteArray = sendDoc.toJson(QJsonDocument::Compact);
                emit sigWallRun(2, QString(byteArray));
            }
        }
    }else if("webWriteLogin" == szcmd){
        QString username = obj.take("username").toString();
        QString userpwd = obj.take("userpwd").toString();
        m_szLog = QString("select activityNum,activityPwd from t_basiconfig");
        QString activityname;
        QString activitypwd;
        if(parent->m_dbquery->exec(m_szLog)){
            int nusername = parent->m_dbquery->record().indexOf("activityNum");
            int nuserpwd = parent->m_dbquery->record().indexOf("activityPwd");
            while(parent->m_dbquery->next())
            {
                activityname = parent->m_dbquery->value(nusername).toString();
                activitypwd = parent->m_dbquery->value(nuserpwd).toString();
            }
        }
        QJsonObject sendobj;
        sendobj.insert("cmd", "webWriteLogin");
        if(username == activityname && userpwd == activitypwd){
            sendobj.insert("result", "ok");
        }else if(username.length() < 1 || userpwd.length() < 1){
            sendobj.insert("result", "null");
        }else{
            sendobj.insert("result", u8"用户名或密码错误!");
        }
        QJsonDocument jsonDoc;
        jsonDoc.setObject(sendobj);
        QByteArray byteArray = jsonDoc.toJson(QJsonDocument::Compact);
        sendToClient(socket, QString(byteArray));
        qDebug() << u8"手写端登录=" << byteArray.data();
    }
}
